/**
 * @author M_xiaohan
 * @date 2018/4/26
 * @Description:
*/

import React from 'react';
import ReactDOM from 'react-dom';
import { connect } from 'dva';
import {
  ListView,
  Drawer,
  Icon,
  List,
  NavBar,
  Flex,
  SearchBar,
} from 'antd-mobile';
import styles from './internalTypeDetail.css';


class InternalTypeDetail extends React.Component {
  constructor(props) {
    super(props);
    const dataSource = new ListView.DataSource({
      rowHasChanged: (row1, row2) => row2,
    });
    this.state = {
      dataSource,
      isLoading: true,
      height: document.documentElement.clientHeight,
      showNavBar: 'block',
      showSearchBar: 'none',
      docked: false,
      navbarTitle: '蔬菜类',
      nextPage: Number,
      hasNextPage: Boolean,
      carListNum: this.props.carListNum,
      searching: false,
      searchValue: '',
      selected: '',
    };
  }

  componentDidMount() {
    this.props.dispatch({
      type: 'internaltradetype/fetchInternaltradetypeList',
      payload: {
        pageNum: 0,
      },
    });
    this.initDataSource();
    this.autoFocusInst.focus();
  }


  componentWillReceiveProps(nextProps) {
    this.setState({
      dataSource: this.state.dataSource.cloneWithRows(nextProps.internaltradetypeDetail.internaltradetypeDetailList), // eslint-disable-line
      isLoading: false,
    });
  }
  onDock(d) {
    this.setState({
      [d]: !this.state[d],
    });
  }

  onEndReached = () => {
    if (this.state.isLoading && !this.state.hasMore) {
      return;
    }
    this.setState({
      isLoading: true,
    });
    if (this.props.internaltradetypeDetail.hasNextPage) {
      if (this.state.searching) {
        this.props.dispatch({
          type: 'internaltradetypeDetail/searchData',
          payload: {
            // internalType: this.state.navbarTitle,
            internalName: this.state.searchValue,
            pageNum: this.props.internaltradetypeDetail.nextPage,
          },
        });
      } else {
        this.props.dispatch({
          type: 'internaltradetypeDetail/fetchInternaltradetypeDetalList',
          payload: {
            internalType: this.state.navbarTitle,
            pageNum: this.props.internaltradetypeDetail.nextPage,
          },
        });
      }
    } else {
      this.setState({
        isLoading: false,
      });
    }
  }

  onCancelShowSearchButton = () => {
    this.props.dispatch({
      type: 'internaltradetypeDetail/fetchInternaltradetypeDetalList',
      payload: {
        internalType: this.state.navbarTitle,
        pageNum: 0,
      },
    });
    this.autoFocusInst.doClear();
    this.setState({
      showNavBar: 'block',
      showSearchBar: 'none',
      searching: false,
    });
  }
  onChange= (searchValue) => {
    this.setState({ searchValue });
  };
  getBlur = () => {
    this.autoFocusInst.focus();
  }
  searchData = (value) => {
    this.setState({
      searching: true,
      searchValue: value,
    });
    this.props.dispatch({
      type: 'internaltradetypeDetail/searchData',
      payload: {
        internalName: value,
        // internalType: this.state.navbarTitle,
        pageNum: 0,
      },
    });
  }


  initDataSource = () => {
    const navBarHeight = ReactDOM.findDOMNode(this.nav).offsetHeight; // eslint-disable-line
    const listViewheight = document.documentElement.clientHeight - navBarHeight - 50;
    this.setState({
      navbarTitle: this.props.location.query ? this.props.location.query.internalType : '蔬菜类',
      isLoading: false,
      height: listViewheight,
    });
  }
  handleSideBarClick = (item) => {
    this.setState({
      navbarTitle: item.internalType,
      selected: item.id,
    });
    const queryParams = {
      internalType: item.internalType,
      pageNum: 0,
    };
    this.props.dispatch({
      type: 'internaltradetypeDetail/fetchInternaltradetypeDetalList',
      payload: queryParams,
    });
  }

  showSearchBar = () => {
    this.setState({ showNavBar: 'none', showSearchBar: 'block' });
    this.getBlur();
  }

  addGoodToCar = (parms) => {
    const goodInfos = {
      customerId: 1,
      count: 0,
      internalTradeId: parms.id,
    };
    this.props.dispatch({ type: 'internaltradetypeDetail/addToCar', payload: goodInfos });
  }

  render() {
    const { InternaltradetypeList } = this.props.internaltradetype;
    const { internaltradetypeDetailList } = this.props.internaltradetypeDetail;
    const sidebar = (
      <List>
        {InternaltradetypeList.map((item) => {
        return (
          <List.Item
            key={item.id}
            thumb="./src/assets/img/food.png"
            className={this.state.selected === item.id ? styles.selected : styles.unSelected}
            onClick={() => this.handleSideBarClick(item)}
          >
            {item.internalType}
          </List.Item>);
        })}
      </List>);


    const separator = (sectionID, rowID) => (
      <div
        key={`${sectionID}-${rowID}`}
        style={{
          backgroundColor: '#F5F5F9',
          height: 8,
          borderTop: '1px solid #ECECED',
          borderBottom: '1px solid #ECECED',
        }}
      />
    );
    const index = internaltradetypeDetailList - 1;
    const row = (rowData, rowID) => {
      if (index < 0) {
        return <div style={{ height: '60px', padding: 25 }}>抱歉哦，没有数据！</div>;
      }
      return (
        <div key={rowID} style={{ padding: '0 15px' }}>
          <Flex
            justify="between"
            style={{ display: '-webkit-box', display: 'flex', padding: '15px 0' }} // eslint-disable-line
          >
            <div style={{ lineHeight: 1 }}>
              <div style={{ marginBottom: '8px', fontWeight: 'bold', fontSize: '18px', color: '#FF6E27' }}>{rowData.internalName}</div>
              <div>单位：<span>{rowData.unitName}</span></div>
            </div>
            <div
              className={!rowData.hasAddToCar ? styles.carBg : styles.carBgSelected}
              onClick={() => this.addGoodToCar(rowData)}
            >
              <img
                style={{ width: 28, margin: 8, color: '#9cdcf0' }}
                src={!rowData.hasAddToCar ? './src/assets/img/addCar.png' : './src/assets/img/addedCar.png'}
                alt="加入购物车"
              />
            </div>
          </Flex>
        </div>
      );
    };
    const toolbar = () => {
      // if (this.state.showNavBar) {
      return (
        <div
          ref={el => this.nav = el} // eslint-disable-line
        >
          <div style={{ display: this.state.showNavBar }}>
            <NavBar
              mode="light"
              icon={<Icon key="2" type="ellipsis" />}
              onLeftClick={() => this.onDock('docked')}
              rightContent={[
                <Icon key="2" type="search" onClick={() => this.showSearchBar()} />,
              ]}
            > {this.state.navbarTitle}
            </NavBar>
          </div>
          <div style={{ display: this.state.showSearchBar }}>
            <SearchBar
              ref={ref => this.autoFocusInst = ref} // eslint-disable-line
              // key="5"
              value={this.state.searchValue}
              placeholder="请输入搜索详情"
              // maxLength={8}
              onChange={this.onChange}
              style={{ backgroundColor: '#FFFFFF' }}
              onCancel={this.onCancelShowSearchButton}
              onBlur={this.getBlur}
              onSubmit={this.searchData}
            />
          </div>
        </div>
      );
    };
    return (
      <div style={{ height: '100%' }}>
        { toolbar() }
        <div style={{ position: 'relative' }}>
          <Drawer
            className={styles.myDrawer}
            style={{ minHeight: this.state.height }}
            contentStyle={{ textAlign: 'center', paddingLeft: 5, paddingRight: 5 }}
            // sidebarStyle={{ padding: 10 }}
            sidebar={sidebar}
            docked={this.state.docked}
            touch
          >
            <ListView
              dataSource={this.state.dataSource}
              renderFooter={() => (
                <div style={{ padding: 30, textAlign: 'center' }}>
                  {this.state.isLoading ? '吃奶的力气加载中...' : '我是有底线的'}
                </div>
              )}
              renderRow={row}
              style={{
                height: this.state.height,
                overflow: 'auto',
              }}
              renderSeparator={separator}
              pageSize={4}
              useBodyScorll
              onEndReached={this.onEndReached}
              onEndReachedThreshold={10}
              horizontal={false}
            />
          </Drawer>
        </div>
      </div>
    );
  }
}


export default connect(({ internaltradetype, internaltradetypeDetail, global }) => ({
  internaltradetype,
  internaltradetypeDetail,
  carListNum: global.carListNum,
}))(InternalTypeDetail);
